<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import '@/assets/css/tagStyle.css'
import '@/assets/css/fancySearchForm.css'

import { ref, onMounted } from 'vue'
import {  clientListService,  clientAddService,  clientUpdateService,  clientDeleteService} from '@/api/client.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTokenStore } from '@/stores/token.js' 
const tokenStore = useTokenStore();
console.log(tokenStore.token); 

// 客户列表数据及分页
const clients = ref([])
const state = ref('全部')         
const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 抽屉控制
const visibleDrawer = ref(false)
const title = ref('')

// 表单模型
const clientModel = ref({
  name: '',
  contactPerson: '',
  contactPhone: '',
  email: '',
  address: '',
  contractStart: '',
  contractEnd: '',
  state: ''
})

// 获取客户列表
const clientList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    state: state.value === '全部' ? null : state.value

  }
  try {
    const result = await clientListService(params, tokenStore.token)
    clients.value = result.data.items
    total.value = result.data.total
  } catch (error) {
    ElMessage.error('获取客户列表失败')
  }
}

onMounted(() => {
  clientList()
})

// 分页
const onSizeChange = size => {
  pageSize.value = size
  clientList()
}

const onCurrentChange = num => {
  pageNum.value = num
  clientList()
}

// 添加客户
const addclient = async clickState => {
  clientModel.value.state = clickState
  let result = await clientAddService(clientModel.value);
    ElMessage.success(result.msg? result.msg:'添加成功')
    visibleDrawer.value=false;
    clientList();
}

// 编辑前清空表单
const clearData = () => {
  visibleDrawer.value = true
  title.value = '添加客户'
  clientModel.value = {
    name: '',
    contactPerson: '',
    contactPhone: '',
    email: '',
    address: '',
    contractStart: '',
    contractEnd: '',
    state: ''
  }
}

// 填充表单
const showDialog = row => {
  visibleDrawer.value = true
  title.value = '编辑客户'
  Object.assign(clientModel.value, row)
}

// 更新客户
const updateclient = async clickState => {
  clientModel.value.state = clickState
  try {
    const result = await clientUpdateService(clientModel.value)
    ElMessage.success(result.msg || '编辑成功')
    visibleDrawer.value = false
    clientList()
  } catch (error) {
    ElMessage.error('编辑失败')
  }
}

// 删除客户
const deleteclient = row => {
  ElMessageBox.confirm('你确定要删除该客户吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await clientDeleteService(row.id)
        ElMessage.success('删除成功')
        clientList()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作'
      })
    })
}

// 发布按钮
const handlePublish = () => {
  if (title.value === '添加客户') {
    addclient('合作中')
  } else {
    updateclient('合作后')
  }
}

// 草稿按钮
const handleSaveDraft = () => {
  if (title.value === '添加客户') {
    addclient('合作中')
  } else {
    updateclient('合作后')
  }
}

// 重置筛选条件
const resetFilter = () => {
  state.value = ''
  pageNum.value = 1
  clientList()
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>客户管理</span>
        <div class="extra">
          <el-button type="primary" @click="clearData">添加客户</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索表单 -->
<el-form inline class="fancy-search-form">
  <el-form-item label="客户状态：">
    <el-select
      v-model="state"
      placeholder="请选择状态"
      clearable
      style="width: 160px"
    >
      <el-option label="全部" value="全部" />
      <el-option label="合作中" value="合作中" />
      <el-option label="合作后" value="合作后" />
    </el-select>
  </el-form-item>

  <el-form-item>
    <el-button type="primary" @click="clientList">搜索</el-button>
    <el-button @click="resetFilter">重置</el-button>
  </el-form-item>
</el-form>


    <!-- 客户列表 -->

  <el-table :data="clients" style="width: 100%" class="custom-table" border highlight-current-row>
     <el-table-column label="序号" width="100" type="index">
      <template #default="{ $index }">
        <span class="tag tag-blue">{{ $index + 1 }}</span>
      </template>
    </el-table-column>

    <el-table-column label="客户名" width="200" prop="name">
      <template #default="{ row }">
        <span class="tag tag-blue">{{ row.name }}</span>
      </template>
    </el-table-column>

    <el-table-column label="联系方式" prop="contactPhone">
      <template #default="{ row }">
        <span class="tag tag-orange">{{ row.contactPhone }}</span>
      </template>
    </el-table-column>

    <el-table-column label="合作起始时间" prop="contractStart">
      <template #default="{ row }">
        <span class="tag tag-purple">{{ row.contractStart }}</span>
      </template>
    </el-table-column>

    <el-table-column label="合作结束时间" prop="contractEnd">
      <template #default="{ row }">
        <span class="tag tag-cyan">{{ row.contractEnd }}</span>
      </template>
    </el-table-column>

    <el-table-column label="状态" prop="state" width="100">
      <template #default="{ row }">
        <span
          class="tag"
          :class="row.state === '合作中' ? 'tag-green' : 'tag-gray'"
        >
          {{ row.state }}
        </span>
      </template>
    </el-table-column>

    <el-table-column label="操作" width="160">
      <template #default="{ row }">
        <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)" />
        <el-button :icon="Delete" circle plain type="danger" @click="deleteclient(row)" />
      </template>
    </el-table-column>

    <template #empty>
      <el-empty description="没有数据" />
    </template>
  </el-table>



    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <!-- 抽屉表单 -->
<el-drawer
  v-model="visibleDrawer"
  :title="title"
  direction="rtl"
  size="50%"
  class="fancy-dialog"
>
  <el-form :model="clientModel" label-width="100px" class="fancy-form">
    <el-form-item label="客户姓名" class="fancy-input">
      <el-input v-model="clientModel.name" placeholder="请输入客户姓名" />
    </el-form-item>

    <el-form-item label="联系人姓名" class="fancy-input">
      <el-input v-model="clientModel.contactPerson" placeholder="请输入联系人姓名" />
    </el-form-item>

    <el-form-item label="联系人电话" class="fancy-input">
      <el-input v-model="clientModel.contactPhone" placeholder="请输入手机号" />
    </el-form-item>

    <el-form-item label="联系邮箱" class="fancy-input">
      <el-input v-model="clientModel.email" placeholder="请输入邮箱" />
    </el-form-item>

    <el-form-item label="联系地址" class="fancy-input">
      <el-input v-model="clientModel.address" placeholder="请输入联系地址" />
    </el-form-item>

    <el-form-item label="签约时间" class="fancy-input">
      <el-date-picker
        v-model="clientModel.contractStart"
        type="date"
        placeholder="请选择签约时间"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        style="width: 100%"
      />
    </el-form-item>

    <el-form-item label="合约到期时间" class="fancy-input">
      <el-date-picker
        v-model="clientModel.contractEnd"
        type="date"
        placeholder="请选择结束时间"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        style="width: 100%"
      />
    </el-form-item>

    <el-form-item label="客户状态" class="fancy-input">
      <el-select v-model="clientModel.state" placeholder="请选择客户状态">
        <el-option label="合作中" value="合作中" />
        <el-option label="合作后" value="合作后" />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button
        type="primary"
        class="fancy-btn confirm"
        @click="handlePublish"
      >
        发布
      </el-button>
      <el-button
        type="info"
        class="fancy-btn cancel"
        @click="handleSaveDraft"
      >
        合作后
      </el-button>
    </el-form-item>
  </el-form>
</el-drawer>

  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}

.el-button > .el-icon + span {
  margin-left: 4px;
}

/* 表格整体样式 */
.custom-table {
  border-radius: 10px;
  overflow: hidden;
  background-color: #fff;
}


</style>